#include<iostream>
#include<unistd.h>
#include<string>
#include<cstdio>
#include<cstring>
#include<assert.h>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;


int main()
{
    //1.创建管道
    int pipefd[2] = {0};    //pipefd[0]：读端， pipefd[1]：写端
    int n = pipe(pipefd);   //pipefd是输出型参数，期望通过调用它获得被打开的文件fd

    assert(n != -1);
    (void)n;                //防止release版本下报警

#ifdef DEBUG
    cout<<"pipefd[0]: "<<pipefd[0]<<endl; //3
    cout<<"pipefd[1]: "<<pipefd[1]<<endl; //4
#endif

    //2.创建子进程
    pid_t id = fork();
    assert(id != -1);
    if(id == 0)
    {
        //子进程
        //3.构建单项通信的信道，假设父进程写入，子进程读取
        //3.1 关闭子进程不需要的fd
        close(pipefd[1]);
        char buffer[1024];
        while(1)
        {
            ssize_t s = read(pipefd[0],buffer,sizeof(buffer)-1);
            if(s > 0)
            {
                buffer[s] = 0;
                cout<<"child get a message["<<getpid()<<"] Father#"<<buffer<<endl;
            }
        }  
        close(pipefd[0]); 
        exit(0);
    }
    else
    {
        //父进程
        //3.构建单项通信的信道，假设父进程写入，子进程读取 
        //3.1 关闭该进程不需要的fd
        close(pipefd[0]);
        string message = "我是父进程，我正在给你发消息";
        int count = 0;
        char send_buffer[1024];
        while (1)
        {
            //3.2构建一个变化的字符串
            snprintf(send_buffer,sizeof(send_buffer),"%s[%d]:%d",message.c_str(),getpid(),count++);
            //3.3写入/发送消息
            write(pipefd[1],send_buffer,strlen(send_buffer));
            //3.4故意sleep
            sleep(1);
        }
    }

    pid_t ret = waitpid(id,nullptr,0);  //等待子进程
    assert(ret > 0);
    (void) ret;

    close(pipefd[1]);

    return 0;
}